package com.gitee.cui.netty.echoServer;

import com.gitee.cui.netty.NettyDemoConfig;
import com.gitee.cui.util.Dateutil;
import com.gitee.cui.util.Logger;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 回显服务客户端程序
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/10/22 16:18
 **/
public class NettyEchoClient {

    private int serverPort;

    private String serverIp;

    private Bootstrap bootstrap = new Bootstrap();

    NettyEchoClient(String ip, int port) {
        this.serverIp = ip;
        this.serverPort = port;
    }

    public static void main(String[] args) {
        new NettyEchoClient(NettyDemoConfig.SOCKET_SERVER_IP, NettyDemoConfig.SOCKET_SERVER_PORT).runClient();
    }

    private void runClient() {
        // 创建反应器轮询组
        EventLoopGroup worker = new NioEventLoopGroup();
        try {
            // 1、设置反应器轮询组
            bootstrap.group(worker);
            // 2、设置nio通道的类型
            bootstrap.channel(NioSocketChannel.class);
            // 3、设置监听端口
            bootstrap.remoteAddress(serverIp, serverPort);
            // 4、设置通道的参数
            bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            // 5、装配子通道流水线
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                /**
                 * 有连接到达时，会创建一个通道
                 * @param ch
                 * @throws Exception
                 */
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    // 管理子通道中的Handler
                    // 向子通道流水线添加一个Handler
                    ch.pipeline().addLast(NettyEchoClientHandler.INSTANCE);
                }
            });

            ChannelFuture future = bootstrap.connect();
            // 添加监听
            future.addListener(listener -> {
                if (listener.isSuccess()) {
                    Logger.info("EchoClient客户端连接成功！");
                } else {
                    Logger.info("EchoClient客户端连接失败！");
                }
            });
            // 阻塞，直到连接成功
            future.sync();

            // 控制台输入内容
            Channel channel = future.channel();
            Scanner scanner = new Scanner(System.in);
            Logger.tcfo("请输入发送内容：");
            while (scanner.hasNext()) {
                // 获取输入内容
                String value = scanner.next();
                byte[] bytes = (Dateutil.getNow() + ">>" + value).getBytes(StandardCharsets.UTF_8);
                // 发送ByteBuf
                ByteBuf buffer = channel.alloc().buffer();
                buffer.writeBytes(bytes);
                channel.writeAndFlush(buffer);
                Logger.tcfo("请输入发送内容：");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 释放所有资源，包括创建的线程
            worker.shutdownGracefully();
        }
    }
}
